﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using HigLabo.Net.Extensions;
using Newtonsoft.Json.Linq;

namespace HigLabo.Net.Twitter
{
    /// <summary>
    /// 
    /// </summary>
    public class BoundingBox : ResponseObject
    {
        /// <summary>
        /// 
        /// </summary>
        public CoordinateCollection Coordinates { set; get; }
        /// <summary>
        /// 
        /// </summary>
        public String Type { set; get; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="jsonText"></param>
        public BoundingBox(String jsonText)
        {
            this.SetProperty(jsonText);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jsonText"></param>
        public override void SetProperty(string jsonText)
        {
            var d = this.SetData(jsonText);

            object objOut = null;
            Double la = 0;
            Double lo = 0;

            this.Type = d.ToString("type");
            d.TryGetValue("coordinates", out objOut);
            JContainer val = (JContainer)objOut;

            if (val != null)
            {
                this.Coordinates = new CoordinateCollection();
                for (int i = 0; i < val.Count(); i++)
                {
                    var v1 = val.ElementAt(i);
                    if (v1.Type == JTokenType.Array)
                    {
                        for (int j = 0; j < v1.Count(); j++)
                        {
                            var v2 = v1.ElementAt(j);
                            lo = Double.Parse(v2.ElementAt(0).ToString());
                            la = Double.Parse(v2.ElementAt(1).ToString());
                            this.Coordinates.Add(new Coordinate(la, lo));
                        }
                    }
                    else// if (v1.Type == JTokenType.Float)
                    {
                        lo = Double.Parse(val.ElementAt(i).ToString());
                        la = Double.Parse(val.ElementAt(i + 1).ToString());
                        this.Coordinates.Add(new Coordinate(la, lo));
                        break;
                    }
                }
            }
        }
    }
}
